<template>
  <div class="container">
    <h5>请选择1D Profiler的excel文件</h5>
    <!-- 文件上传区域 -->
    <div class="upload-section">
      <el-upload
        class="upload-demo"
        :action="`${config.baseURL}/profile/upload`"
        :on-success="handleUploadSuccess"
        :on-error="handleUploadError"
        :multiple="true"
        :limit="8"
        :show-file-list="false"
        accept=".xlsx,.xls">
        <el-button type="primary">上传Excel文件</el-button>
      </el-upload>
    </div>

    <!-- 文件列表区域 -->
    <div class="files-section">
      <div v-for="(file, index) in uploadedFiles" :key="file.id" class="file-item">
        <el-checkbox v-model="file.selected" @change="handleCheckboxChange">
          {{ file.name }}
        </el-checkbox>
      </div>
    </div>

    <!-- 图表区域 -->
    <div class="chart-section" v-if="uploadedFiles.length > 0">
      <div ref="chartRef" style="width: 100%; height: 600px"></div>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import axios from '../../plugins/axios'
import { config } from '../../config'
import { ElMessage } from 'element-plus'

// 图表容器引用
const chartRef = ref(null)
let myChart = null

// 上传的文件列表
const uploadedFiles = ref([])

// 图表颜色数组
const colors = [
  '#5470c6', '#91cc75', '#fac858', '#ee6666',
  '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
]

// 初始化图表
const initChart = async () => {
  await nextTick()
  if (!chartRef.value) return

  if (myChart) {
    myChart.dispose() // 销毁之前的图表实例
  }
  myChart = echarts.init(chartRef.value) // 初始化新的图表实例
}

// 更新图表数据
const updateChart = () => {
  if (!myChart || uploadedFiles.value.length === 0) return

  // 获取选中的文件数据
  const selectedFiles = uploadedFiles.value.filter(file => file.selected)

  // 如果没有选中的文件，清空图表
  if (selectedFiles.length === 0) {
    myChart.clear();
    return;
  }

  // 构建图表数据
  const series = [
    // 添加两条垂直的红色虚线
    {
      name: 'Boundary Line 1',
      type: 'line',
      markLine: {
        symbol: ['none', 'none'],
        silent: true,
        data: [{ xAxis: 150 }],
        lineStyle: {
          color: '#ff0000',
          type: 'dashed',
          width: 1
        }
      }
    },
    {
      name: 'Boundary Line 2',
      type: 'line',
      markLine: {
        symbol: ['none', 'none'],
        silent: true,
        data: [{ xAxis: -150 }],
        lineStyle: {
          color: '#ff0000',
          type: 'dashed',
          width: 1
        }
      }
    },
    // 原有的数据线
    ...selectedFiles.map((file, index) => ({
      name: file.name,
      type: 'line',
      smooth: true,
      symbol: 'none',
      data: file.data.map(item => [item.p, item.v]),
      lineStyle: {
        color: colors[index % colors.length]
      }
    }))
  ]

  // 配置图表选项
  const option = {
    title: {
      text: 'Vertical Profile Data'
    },
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      min: -180,
      max: 180,
      interval: 20,
      axisLabel: {
        formatter: '{value}mm'  // 将 ° 改成 mm
      },
      scale: false
    },
    yAxis: {
      type: 'value',
      min: 0.2,
      max: 1.2,
      interval: 0.2
    },
    series: series
  }

  // 设置图表选项
  myChart.setOption(option, true);
}

// 监听文件列表变化
watch(() => uploadedFiles.value, async () => {
  await initChart()
  updateChart()
}, { deep: true })

// 监听窗口大小变化
const handleResize = () => {
  if (myChart) {
    myChart.resize()
  }
}

// 组件挂载时初始化图表
onMounted(async () => {
  await initChart()
  updateChart()
  window.addEventListener('resize', handleResize)
})

// 组件卸载时销毁图表
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
})

// 文件上传成功回调
const handleUploadSuccess = (response, file) => {
  console.log('后端返回的数据:', response.data) // 打印后端返回的数据

  // 转换数据格式
  const formattedData = response.data.map(item => ({
    p: Number(item.mm), // 确保 p 是数值
    v: Number(item.ma)  // 确保 v 是数值
  }))

  uploadedFiles.value.push({
    id: Date.now(),
    name: file.name,
    selected: true,
    data: formattedData // 使用格式化后的数据
  })
}

// 文件上传失败回调
const handleUploadError = (error) => {
  console.error('Upload failed:', error)
  ElMessage.error('文件上传失败')
}

// 复选框变化回调
const handleCheckboxChange = () => {
  updateChart() // 更新图表
}
</script>
<style scoped>
.container {
  padding: 20px;
}

.upload-section {
  margin-bottom: 20px;
}

.files-section {
  margin-bottom: 20px;
  display: flex;  /* 添加flex布局 */
  flex-wrap: wrap;  /* 允许换行 */
  gap: 20px;  /* 添加间距 */
}

.file-item {
  margin: 0;  /* 移除垂直margin */
  flex: 0 0 auto;  /* 防止项目被拉伸 */
}

.chart-section {
  margin-top: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 200px);  /* 设置固定高度，减去上方内容的大致高度 */
  overflow: hidden;  /* 防止内容溢出 */
}
</style>